package com.song.controller;

import com.song.domain.Order;
import com.song.model.PageResult;
import com.song.service.OrderService;
import com.song.service.CustomerService;
import com.song.service.MaterialService;
import org.springframework.validation.annotation.Validated;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/orders")
@Validated
public class OrderController {
    private final OrderService service;
    private final CustomerService customerService;
    private final MaterialService materialService;

    public OrderController(OrderService service, CustomerService customerService, MaterialService materialService) {
        this.service = service;
        this.customerService = customerService;
        this.materialService = materialService;
    }

    @GetMapping
    public PageResult<Order> list(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "10") int size,
                                  @RequestParam(required = false) String status,
                                  @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") java.util.Date startDate,
                                  @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") java.util.Date endDate,
                                  @RequestParam(required = false) String customerName) {
        List<Order> items = service.list(page, size, status, startDate, endDate, customerName);
        int total = service.count(status, startDate, endDate, customerName);
        return new PageResult<>(items, total);
    }

    @GetMapping("/{id}")
    public Order get(@PathVariable Long id) {
        return service.get(id);
    }

    @PostMapping
    public Order create(@Valid @RequestBody Order order) {
        return service.create(order);
    }

    @PutMapping("/{id}")
    public Order update(@PathVariable Long id, @Valid @RequestBody Order order) {
        order.setId(id);
        return service.update(order);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        service.delete(id);
    }


    @GetMapping("/export/xlsx")
    public void exportXlsx(@RequestParam(required = false) String status,
                           @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") java.util.Date startDate,
                           @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") java.util.Date endDate,
                           @RequestParam(required = false) String customerName,
                           javax.servlet.http.HttpServletResponse response) throws java.io.IOException {
        List<Order> items = service.listAll(status, startDate, endDate, customerName);
        org.apache.poi.xssf.usermodel.XSSFWorkbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
        org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet("Orders");
        org.apache.poi.ss.usermodel.Row header = sheet.createRow(0);
        String[] heads = {"ID","客户","材料","数量","开始日期","结束日期","状态","总价","创建时间"};
        for (int i=0;i<heads.length;i++) header.createCell(i).setCellValue(heads[i]);
        java.text.SimpleDateFormat fmt = new java.text.SimpleDateFormat("yyyy-MM-dd");
        java.text.SimpleDateFormat fmt2 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int r = 1;
        for (Order o : items) {
            org.apache.poi.ss.usermodel.Row row = sheet.createRow(r++);
            row.createCell(0).setCellValue(o.getId());
            row.createCell(1).setCellValue(customerName(o.getCustomerId()));
            row.createCell(2).setCellValue(materialsText(o));
            row.createCell(3).setCellValue(o.getQuantity()!=null?o.getQuantity():0);
            row.createCell(4).setCellValue(o.getStartDate()!=null?fmt.format(o.getStartDate()):"");
            row.createCell(5).setCellValue(o.getEndDate()!=null?fmt.format(o.getEndDate()):"");
            row.createCell(6).setCellValue(statusLabel(o.getStatus()));
            row.createCell(7).setCellValue(o.getTotalPrice()!=null?o.getTotalPrice().doubleValue():0);
            row.createCell(8).setCellValue(o.getCreatedAt()!=null?fmt2.format(o.getCreatedAt()):"");
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=orders.xlsx");
        java.io.OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        wb.close();
    }

    private String customerName(Long id) {
        if (id == null) return "";
        com.song.domain.Customer c = customerService.get(id);
        return c != null ? c.getName() : String.valueOf(id);
    }

    private String materialName(Long id) {
        if (id == null) return "";
        com.song.domain.Material m = materialService.get(id);
        return m != null ? m.getName() : String.valueOf(id);
    }

    private String materialsText(Order o) {
        java.util.List<com.song.domain.OrderItem> items = o.getItems();
        if (items != null && !items.isEmpty()) {
            java.util.List<String> parts = new java.util.ArrayList<>();
            for (com.song.domain.OrderItem it : items) {
                String n = materialName(it.getMaterialId());
                parts.add(n + " x" + (it.getQuantity()!=null?it.getQuantity():0));
            }
            return String.join("、", parts);
        }
        return materialName(o.getMaterialId());
    }

    private String statusLabel(String s) {
        if (s == null || s.trim().isEmpty()) return "";
        String t = s.trim();
        if ("0".equals(t)) return "已结束";
        if ("1".equals(t)) return "进行中";
        if ("2".equals(t)) return "未开始";
        String u = t.toUpperCase();
        if ("COMPLETED".equals(u)) return "已结束";
        if ("IN_PROGRESS".equals(u)) return "进行中";
        if ("OPEN".equals(u)) return "未开始";
        return t;
    }

    @GetMapping("/summary")
    public java.util.Map<String, Object> summary() {
        java.math.BigDecimal revenue = service.sumTotal();
        java.util.Map<String, Object> map = new java.util.HashMap<>();
        map.put("revenue", revenue);
        return map;
    }
}